package com.shanghaionstar.alarm;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 闹钟辅助类
 *
 * Created by Yonglang Hong on 2017/1/11.
 */
public class AlarmHelper {

    /**
     * 设置闹钟
     * @param context
     * @param action
     * @param expireDate 到期时间
     * @param days       到期时间相隔天数
     */
    public static void setAlarm(Context context, String action, String expireDate, int days) {
        Intent intent = new Intent(context, AlarmReceiver.class);
        intent.setAction(action);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = dateFormat.parse(expireDate);
            calendar.setTimeInMillis(date.getTime());
            calendar.add(Calendar.DAY_OF_YEAR,-days);
            calendar.add(Calendar.HOUR_OF_DAY, 9);
            AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
        } catch (Exception ex) {
        }
    }

    /**
     * 取消闹钟
     * @param context
     * @param action
     */
    public static void cancelAlarm(Context context, String action) {
        Intent intent = new Intent(context, AlarmReceiver.class);
        intent.setAction(action);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(sender);
    }

}
